/**
 * Created by jijin on 2017/7/8.
 *
 * android 侧栏抽屉
 */

import React, { Component } from 'react';
import {
  DrawerLayoutAndroid,
  View
} from 'react-native';
import MenuHeader from "./android/menu-header";
import MenuList from "./android/menu-list";

export default class Menu extends Component {
  constructor(props) {
    super(props);
    let {initialEntry, entries} = this.props;
    this.state = {
      selectedItem: initialEntry || entries[0].id
    }
  }

  _onSectionChange = (section) => {
    this.setState({selectedItem: section});
    this._drawer.closeDrawer();
  };

  _renderNavigationView = () => {
    return (
      <View style={this.props.containerStyle}>
        <MenuHeader userInfo={this.props.userInfo}/>
        <MenuList
          items={this.props.entries}
          selectedItem={this.state.selectedItem}
          tintColor={this.props.tintColor}
          onSectionChange={this._onSectionChange}
        />
      </View>
    )
  };

  _openMenu() {
    // alert(this._drawer);
    this._drawer.openDrawer();
  }

  _renderContent() {
    let Element = this.props.entries.find(entry => entry.id === this.state.selectedItem).element;
    if (Element) {
      return React.cloneElement(Element, {openMenu: this._openMenu.bind(this)});
    }
  }

  render() {
    return (
      <DrawerLayoutAndroid
        ref={(ref) => { this._drawer = ref;}}
        {...this.props}
        renderNavigationView={this._renderNavigationView}>
        {this._renderContent()}
      </DrawerLayoutAndroid>
    )
  }
}